/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React, {Component} from 'react';
import {
    Text,
    View,
    StyleSheet,
    ScrollView,
    TouchableOpacity,
    DeviceEventEmitter
} from 'react-native';

import RNBluetoothPrinter from '@react-native-bluetooth-printer'

const Button = ({title, onPress, style, titleStyle}) => <TouchableOpacity
    style={[styles.btnItemView, style]}
    onPress={onPress}
>
    <Text style={[styles.btnItemStyle, titleStyle]}>{title}</Text>
</TouchableOpacity>;

type Props = {};
export default class App extends Component<Props> {

    constructor(props) {
        super(props);
        this.state = {
            listData: [],
            logisticsName: '蜗牛速配',
            userName: '大梦',
            mobile: '15066886888',
            address: '光谷软件园',
            collection: '大梦',
            currentCount: 1,
            totalCount: 1,
            number: '20181102',
            account: '投道科技',
            storeMobile: '15066886000',
        };
        this.deviceMacArray = [];
    }

    componentDidMount(){
        this.listenerGetList =  DeviceEventEmitter.addListener('BluetoothEvent',(device)=>{
            console.log('listenerGetList---->', device);
            this.updateDeviceList(device);
        });
        this.listenerConnect =  DeviceEventEmitter.addListener('ConnectEvent',(connect)=>{
            console.log('listenerConnect---->', connect);
        });
    }

    onPresOpenBlueTooth = () => {
        RNBluetoothPrinter.openBluetooth();
    };

    onPresCloseBlueTooth = () => {
        RNBluetoothPrinter.closeBluetooth();
    };

    updateDeviceList = (device) => {
        let {listData} = this.state;
        let {mac} = device;
        let macString = mac.replace(/:/g, '');
        let tempData = listData;
        let _index = this.deviceMacArray.findIndex(i => macString === i);
        // console.group('updateDeviceList');
        // console.log('updateDeviceList----> arrayIndex---->', _index);
        // console.log('updateDeviceList----> deviceItem---->', device);
        // console.log('updateDeviceList----> deviceMacItem---->', macString);
        // console.log('updateDeviceList----> deviceMacArray---->', this.deviceMacArray);
        if (_index === -1) {
            tempData.push(device);
            this.deviceMacArray.push(macString);
            listData = tempData;
            this.setState({
                listData,
            })
        }
        // console.log('updateDeviceList----> listData---->', listData);
        // console.groupEnd();
    }

    getDeviceList = async () => {
        this.onPresOpenBlueTooth();
        try {
            let result = await RNBluetoothPrinter.scanForPeripherals();
            console.log('success---->', result);
        } catch (e) {
            console.log('error---->', e);
        }
    };

    connectDevice = async (mac) => {
        try {
            let result = await RNBluetoothPrinter.connect(mac);
            console.log('success---->', result);
        } catch (e) {
            console.log('error---->', e);
        }
    };

    closeDevice = async () => {
        try {
            let result = await RNBluetoothPrinter.close();
            console.log('success---->', result);
        } catch (e) {
            console.log('error---->', e);
        }
    };

    printerStatus = async (mac) => {
        mac = 'DC:0D:30:73:09:80';
        let result = await RNBluetoothPrinter.printerStatus(mac);
    }

    printData = async () => {
        let {logisticsName, userName, mobile, address, collection, currentCount, totalCount, number, account, storeMobile} = this.state;
        let qrCodeData = 'logisticsName:' +  logisticsName
                       + ',userName:' +  userName
                       + ',mobile:' +  mobile
                       + ',address:' +  address
                       + ',collection:' +  collection
                       + ',currentCount:' +  currentCount
                       + ',totalCount:' +  totalCount
                       + ',number:' +  number
                       + ',account:' +  account
                       + ',storeMobile:' +  storeMobile;
        for (let i = 1; i <= totalCount; i++) {
            let count = i + '/' + totalCount;
            let data = {
                logisticsName,
                userName,
                mobile,
                address,
                collection,
                count,
                number,
                account,
                storeMobile,
                qrCodeData,
            };
            try {
                let result = await RNBluetoothPrinter.labelPrint(data);
                console.log('success---->', result);
            } catch (e) {
                console.log('error---->', e);
            }
        }
    }


    render() {
        let {listData} = this.state;
        return (
            <View style={styles.container}>
                <ScrollView style={styles.scrollContent}>
                    {listData.length > 0 && listData.map((item, index) => {
                        return (
                            <TouchableOpacity
                                key={index}
                                style={styles.deviceItemView}
                                onPress={() => this.connectDevice(item.mac)}
                            >
                                <Text style={styles.deviceName}>{item.name}</Text>
                                <Text style={styles.deviceMac}>MAC: {item.mac}</Text>
                            </TouchableOpacity>
                        );
                    })}
                </ScrollView>
                <View style={styles.btnContent}>
                    <Button
                        title={'开启蓝牙'}
                        style={styles.btnItemView}
                        titleStyle={styles.btnItemStyle}
                        onPress={this.onPresOpenBlueTooth}
                    />
                    <Button
                        title={'关闭蓝牙'}
                        style={styles.btnItemView}
                        titleStyle={styles.btnItemStyle}
                        onPress={this.onPresCloseBlueTooth}
                    />
                    <Button
                        title={'获取设备列表'}
                        style={styles.btnItemView}
                        titleStyle={styles.btnItemStyle}
                        onPress={this.getDeviceList}
                    />
                </View>
                <View style={styles.btnContent}>
                    <Button
                        title={'打印机状态'}
                        style={styles.btnItemView}
                        titleStyle={styles.btnItemStyle}
                        onPress={this.printerStatus}
                    />
                    <Button
                        title={'打印测试'}
                        style={styles.btnItemView}
                        titleStyle={styles.btnItemStyle}
                        onPress={this.printData}
                    />
                    <Button
                        title={'断开连接'}
                        style={styles.btnItemView}
                        titleStyle={styles.btnItemStyle}
                        onPress={this.closeDevice}
                    />
                </View>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f60',
    },
    scrollContent: {
        flex: 1,
    },
    btnContent: {
        flexDirection: 'row',
    },
    btnItemView: {
        // width: 200,
        flex: 1,
        height: 50,
        marginVertical: 20,
        marginHorizontal: 10,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#333',
    },
    btnItemStyle: {
        color: '#888',
        fontSize: 15,
    },
    deviceItemView: {
        padding: 15,
        marginVertical: 5,
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#333',
    },
    deviceName: {
        flex: 1.5,
        color: '#888',
        marginRight: 15,
    },
    deviceMac: {
        flex: 2,
        color: '#888',
    },
});